package com.xncoding.freemarker.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

//@Order(4)
//@Component
//@WebFilter(filterName = "webLogFilter", urlPatterns = "/*")
public class WebLogFilter implements Filter {
    private final static Logger logger = LoggerFactory.getLogger(WebLogFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 包装request和response
        RequestWrapper requestWrapper = new RequestWrapper((HttpServletRequest) request);
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
        String reqBody = requestWrapper.getBody();
        // 获取request的相关数据
        logger.info("请求URL : " + requestWrapper.getRequestURL().toString());
        logger.info("请求参数 : " + reqBody);

        //将请求中已存在的参数赋值到newParams中
        Map<String, String[]> newParams = new HashMap<>(requestWrapper.getParameterMap());
        logger.info("请求参数 : " + JSON.toJSONString(newParams));


        CustomParameterRequestWrapper wrapRequest = new CustomParameterRequestWrapper(requestWrapper, newParams);
        request.getParameterMap();
        request = wrapRequest;

        chain.doFilter(request, responseWrapper);
        String res = new String(responseWrapper.getContent(), "UTF-8");
        // 获取response的相关数据
        logger.info("响应数据 : " + new String(responseWrapper.getContent(), "UTF-8"));
        System.out.println(res);
        // 在得到响应的数据之后，response的输出流中就无可用的数据，所以需要巴数据放回去
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(res.getBytes());
        outputStream.flush();
        outputStream.close();
    }

    @Override
    public void destroy() {

    }

}






